<template>
  <div>
    <question
      :questionId="questionId"
      :dialogFormVisible="dialogFormVisible"
      @update:dialogFormVisible="handleUpdate"
      v-if="dialogFormVisible"
      :disabled="editFlag"
    ></question>
    <el-dialog :visible.sync="show" title="上 传"
      ><shangChuan
        :url="url"
        :subject-id="form.subjectId"
        @shangChuanEvent="shangChuanEvent"
      ></shangChuan
    ></el-dialog>
    <el-switch
      v-model="searchType"
      active-text="已分类题目"
      inactive-text="未分类题目"
    />
    <el-form :model="form" inline>
      <el-form-item label="题目名称"
        ><el-input v-model="form.name" placeholder="请输入题目名称"></el-input
      ></el-form-item>
      <el-form-item label="课程" v-if="searchType">
        <el-cascader
          v-model="form.subjectPath"
          :options="subjectTree"
          :props="{ checkStrictly: true, emitPath: true }"
          placeholder="请选择课程"
          filterable
          clearable
          @change="handleSubjectChange"
        ></el-cascader>
      </el-form-item>
      <el-button type="primary" @click="search" icon="el-icon-search"
        >查询</el-button
      >
      <el-button type="primary" @click="add" icon="el-icon-plus"
        >添加</el-button
      >
      <el-button type="primary" @click="upload" icon="el-icon-upload2"
        >上传</el-button
      >
    </el-form>
    <el-table :data="tableData">
      <el-table-column label="课程">
        <template slot-scope="scope">
          {{ getSubject(scope.row.subjectId) }}
        </template>
      </el-table-column>
      <el-table-column label="问题" prop="question"></el-table-column>
      <el-table-column label="选项1" prop="item1"></el-table-column>
      <el-table-column label="选项2" prop="item2"></el-table-column>
      <el-table-column label="选项3" prop="item3"></el-table-column>
      <el-table-column label="选项4" prop="item4"></el-table-column>
      <el-table-column label="答案" prop="answer"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="detailHandler(scope.row)" size="mini" type="text"
            >查看</el-button
          >
          <el-button
            @click="detail(scope.row)"
            v-if="isAdmin"
            size="mini"
            type="text"
            >编辑</el-button
          >
          <el-button
            v-if="isAdmin"
            @click="deleteHandler(scope.row)"
            size="mini"
            type="text"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import questionApi from "@/api/question/index";
import question from "@/views/question/question";
import shangChuan from "./shangChuan.vue";
import host from "@/utils/host";
import subjectApi from "@/api/subject/index";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: { question, shangChuan },
  props: {},
  data() {
    //这里存放数据
    return {
      isAdmin: this.$store.getters.roles.includes("admin"),
      editFlag: false,
      url: "",
      show: false,
      form: { name: "", subjectPath: [], subjectId: null },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      questionId: 0,
      dialogFormVisible: false,
      subjectList: [],
      subjectTree: [],
      searchType: true,
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    getSubject(data) {
      const subject = this.subjectList.find((item) => item.id == data);
      if (subject) {
        return subject.name;
      }
    },
    shangChuanEvent(payload) {
      if (payload == "success") {
        this.show = false;
        this.list(this.currentPage);
        this.getTotal();
      }
    },
    upload() {
      // 检查是否选择了叶子节点
      if (!this.form.subjectId) {
        this.$message({
          message: "请选择课程的叶子节点",
          type: "warning",
        });
        return;
      }

      // 检查选择的节点是否为叶子节点
      const isLeafNode = this.isLeafNode(
        this.form.subjectPath[this.form.subjectPath.length - 1]
      );
      if (!isLeafNode) {
        this.$message({
          message: "请选择课程的叶子节点",
          type: "warning",
        });
        return;
      }

      this.show = true;

      // 直接在URL中去掉参数，通过shangChuan组件的data属性传递
      this.url = `http://${host}:9080/elearning/question/upload`;
    },
    deleteHandler(data) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          questionApi.delete(data).then((res) => {
            this.$message({
              type: "success",
              message: `${res.message}`,
            });
            this.list(this.currentPage);
            this.getTotal();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    add() {
      this.dialogFormVisible = true;
      this.questionId = 0;
      this.editFlag = false;
    },
    search() {
      this.getTotal();
      this.list(1);
      this.currentPage = 1;
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.list(currentPage);
    },
    list: async function (currentPage) {
      if (this.searchType) {
        const res = await questionApi.list(
          this.form.name,
          currentPage,
          this.pageSize,
          this.form.subjectId
        );
        this.tableData = res.data;
      } else {
        const res = await questionApi.noSubjectList(
          this.form.name,
          currentPage,
          this.pageSize
        );
        this.tableData = res.data;
      }
    },
    getTotal: async function () {
      if (this.searchType) {
        const res = await questionApi.getTotal(
          this.form.name,
          this.form.subjectId
        );
        this.total = res.data;
      } else {
        const res = await questionApi.noSubjectTotal(this.form.name);
        this.total = res.data;
      }
    },
    detail(data) {
      this.editFlag = false;
      this.questionId = data.id;
      this.dialogFormVisible = true;
    },
    detailHandler(data) {
      this.editFlag = true;
      this.questionId = data.id;
      this.dialogFormVisible = true;
    },
    handleUpdate(value) {
      if (value.type === "detail") {
        this.dialogFormVisible = value.val;
      }
    },
    handleSubjectChange(value) {
      if (value && value.length > 0) {
        this.form.subjectId = value[value.length - 1];
      } else {
        this.form.subjectId = null;
      }
      this.search();
    },
    getSubjectTree() {
      subjectApi.getAllTree().then((res) => {
        this.subjectTree = this.processTreeData(res.data);
      });
    },
    processTreeData(treeData) {
      return treeData.map((node) => {
        const processedNode = { ...node };

        if (processedNode.children && processedNode.children.length === 0) {
          delete processedNode.children;
        } else if (processedNode.children) {
          processedNode.children = this.processTreeData(processedNode.children);
        }

        return processedNode;
      });
    },
    isLeafNode(nodeId) {
      // 递归查找节点
      const findNode = (nodes, id) => {
        for (const node of nodes) {
          if (node.value === id) {
            // 没有children属性或children为空数组，则为叶子节点
            return !node.children || node.children.length === 0;
          }
          if (node.children && node.children.length > 0) {
            const found = findNode(node.children, id);
            if (found !== null) {
              return found;
            }
          }
        }
        return null;
      };

      return findNode(this.subjectTree, nodeId);
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getSubjectTree();
    this.list(1);
    this.getTotal();
    subjectApi.getAllSubject().then((res) => {
      this.subjectList = res.data;
    });
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped></style>
